package com.ymttest.business.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONArray;

import org.apache.commons.collections.CollectionUtils;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.ymatou.iapi.platformdiscounts.parameter.AddBean;
import com.ymatou.iapi.platformdiscounts.parameter.CalculateBean;
import com.ymatou.iapi.platformdiscounts.parameter.ProductDto;
import com.ymatou.iapi.platformdiscounts.service.AddCall;
import com.ymatou.iapi.platformdiscounts.service.CalculateCall;
import com.ymatou.iapi.proditem.service.GetProductInfoByProductIdCall;
import com.ymatou.iapi.productmanager.parameter.UpdateProductCatalogDto;
import com.ymatou.iapi.productmanager.parameter.UpdateProductCatalogsBean;
import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymatou.iapi.productmanager.service.UpdateProductCatalogsCall;
import com.ymt.core.tool.Logger;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.mongo.jproduct.ProductsWapper;
import com.ymttest.database.redis.discountsWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;

public class DiscountsCallService {
//新商品服务为 java 服务
   public static   boolean IS_NEW_PRO_SERVER =true ;
   /**
    * 若根据条件 有商品就直接获取第一条
    * 若没有就新增
    * @return
    */
	public static JSONObject createProduct() {
		
		String proId = null;
		int sellerId = Integer.parseInt((EnvSetup.getData("autotest_seller1")));
		String sellerName = String.valueOf(EnvSetup
				.getData("autotest_sellerName1"));
		
//		int sellerId = Integer.parseInt((EnvSetup.getData("SellerId")));
//		String sellerName = String.valueOf(EnvSetup
//				.getData("SellerName"));
		int stockNum=100;
		
		Map updateMap = new HashMap();
		
		JSONObject productInfo = null;
		try {
			if (IS_NEW_PRO_SERVER) {

				List<String> proids = ProductManagerCallServiceV2.getProducts(
						sellerId, 0, 1, 15);

				if (CollectionUtils.isEmpty(proids)) {

					updateMap.put("product->catalogList[0]->stock", 1000000);

					updateMap.put("product->catalogList[0]->price", 500);
					updateMap.put("product->catalogList[0]->vipPrice", 500);
					updateMap.put("product->catalogList[0]->newPrice", 500);
					proId = ProductManagerCallServiceV2.addNewProductOnSale(
							sellerId, sellerName, updateMap);

					if (!YmtMongoDriverFactroy.isOnStage) {

						new ProductsWapper().getByProductId(proId);
					}

				} else {
					proId = proids.get(new Random().nextInt(proids.size()));
				}

			} else {

				//updateMap.put("product->Catalogs[0]->Num", stockNum);
				//商品不上架	
				proId = SellerProductCallService
						.addNewProductNotOnSale(sellerId,
								sellerName, updateMap).getJSONObject("Data")
						.getString("ProductId");
				
//				proId = ProductManagerCallServiceV2
//						.addNewProductOnSale(sellerId,
//								sellerName, updateMap);
				AddSellerProductRequest addProdReq = ProductManagerCallServiceV2.initAddSellerProductRequest( sellerId);
				proId=ProductManagerCallServiceV2
						.addNewProductOnSale(addProdReq).getAsJsonObject("Data")
						.get("ProductId").getAsString();
				
				Thread.sleep(5000);

			}

				productInfo = GetProductInfoByProductIdCall
					.GetProductInfoByProductId(proId).getJSONObject("Data")
					.getJSONObject("Product");
				
				
				UpdateProductCatalogsBean aa = new UpdateProductCatalogsBean();
				UpdateProductCatalogDto bb = new UpdateProductCatalogDto();
				
				String catalogId=new JSONObject(JSONArray.fromObject(productInfo.getString("CatalogList")).get(0).toString()).getString("CatalogId");

				bb.setCatalogId(catalogId);
				bb.setUserId(productInfo.getInt("SellerId"));
				bb.setPrice(600);
				bb.setNum(100);
				aa.setProductID(productInfo.getString("ProductId"));
				aa.setUserID(productInfo.getInt("SellerId"));
				aa.setCatalogs(Arrays.asList(bb));
				new UpdateProductCatalogsCall().callAndGetReturnData(aa);
				//UpdateProductCatalogsCall.checkUpdateProductCatalogs(result);

		} catch (Exception e) {

			Logger.info(String.format("###############创建商家 sellerId %s，商品失败",
					sellerId));
		}

		return productInfo;

	}
	
	

	@SuppressWarnings("static-access")
	public static AddBean setAdd() throws JSONException
	{
		AddBean bean=new AddBean();
		Date dNow = new Date(); // 当前时间
        Date dBefore = new Date();
        Date dAfter = new Date();

        Calendar calendar1 = Calendar.getInstance(); // 得到日历
        calendar1.setTime(dNow);// 把当前时间赋给日历
        calendar1.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
        dBefore = calendar1.getTime(); // 得到前一天的时间

        Calendar calendar2 = Calendar.getInstance(); // 得到日历
        calendar2.setTime(dNow);// 把当前时间赋给日历
        calendar2.add(Calendar.DAY_OF_MONTH, 10); // 设置为后十天
        dAfter = calendar2.getTime(); // 得到前一天的时间
        
		int userId=TestDataManager.getRandomIntNum(5);
		int sourceId=TestDataManager.getRandomIntNum(5);
		
		bean.setSourceId(sourceId);
		bean.setBizType(1);
		bean.setUserId(userId);
		//创建一个商品
		String productId=new DiscountsCallService().createProduct().getString("ProductId");
		bean.setProductId(productId);
		bean.setStartTime(dBefore);
		bean.setExpireTime(dAfter);
		
		bean.setAppId("11");
		bean.setRequestId("22");
		return bean;
	}
	
	public static AddCall callAdd(AddBean bean) throws ClientProtocolException, IOException
	{
		AddCall call=new AddCall();
		call.setData(bean);
		call.callService();	
		return call;
	}
	
	
	/**
	 * 设置计算优惠bean
	 * @return
	 * @throws Exception 
	 */
	public static CalculateBean setCalculate() throws Exception 
	{
		Logger.comment("############计新增优惠资格开始#################");
		AddBean addBean=setAdd();
		AddCall addCall=callAdd(addBean);
		Logger.comment("############计新增优惠资格结束#################");
		
		CalculateBean bean=new CalculateBean();
		
		bean.setUserId(addBean.getUserId());
		
		List<ProductDto> products=new ArrayList();
		ProductDto dto=new ProductDto();
		JSONObject obj = GetProductInfoByProductIdCall
				.GetProductInfoByProductId(addBean.getProductId()).getJSONObject("Data")
				.getJSONObject("Product");
		String  price= new JSONObject(JSONArray.fromObject(obj.getString("CatalogList")).get(0).toString()).getString("Price");
		dto.setProductId(addBean.getProductId());
		dto.setPrice(new BigDecimal(price));	
		dto.setsecondCategoryId(obj.getInt("CategoryId"));
		products.add(dto);
		bean.setProducts(products);
		bean.setAppId("11");
		bean.setRequestId("22");
		return bean;
	}
	
	public static CalculateCall callCalculated(CalculateBean bean) throws ClientProtocolException, IOException
	{
		CalculateCall call=new CalculateCall();
		call.setData(bean);
		call.callService();	
		return call;
	}
	
	
	public static void main(String args[]) throws Exception {

		 Logger.comment("#####添加优惠开始:#####");
		 //删除redis 的数据
		  //int userId=TestDataManager.getRandomIntNum(5);//可修改用户
	     int userId=20233860;
		 discountsWapper dis=new discountsWapper();
		 dis.delDiscountTime(userId);
		 dis.getDiscountTime(userId);
	     
		AddBean bean=new AddBean();
		Date dNow = new Date(); // 当前时间
        Date dBefore = new Date();
        Date dAfter = new Date();
        
        Calendar calendar1 = Calendar.getInstance(); // 得到日历
        calendar1.setTime(dNow);// 把当前时间赋给日历
        calendar1.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
        dBefore = calendar1.getTime(); // 得到前一天的时间

        Calendar calendar2 = Calendar.getInstance(); // 得到日历
        calendar2.setTime(dNow);// 把当前时间赋给日历
        calendar2.add(Calendar.DAY_OF_MONTH, 10); // 设置为后十天
        dAfter = calendar2.getTime(); // 得到前一天的时间

		
		int sourceId=TestDataManager.getRandomIntNum(5);
		
		bean.setSourceId(sourceId);
		bean.setBizType(1);
		bean.setUserId(userId);
		//创建一个商品
		 IS_NEW_PRO_SERVER = false;
		String productId=new DiscountsCallService().createProduct().getString("ProductId");///可修改用户
		bean.setProductId(productId);
		bean.setStartTime(dBefore);
		bean.setExpireTime(dAfter);
		
		bean.setAppId("11");
		bean.setRequestId("22");
		
		AddCall call=new AddCall();
		call.setData(bean);
		call.callService();	
		Thread.sleep(5000);
		
		//计算
		Logger.comment("#####计算优惠开始:#####");
       CalculateBean cbean=new CalculateBean();
		cbean.setUserId(bean.getUserId());
		
		List<ProductDto> products=new ArrayList();
		ProductDto dto=new ProductDto();
		JSONObject obj = GetProductInfoByProductIdCall
				.GetProductInfoByProductId(bean.getProductId()).getJSONObject("Data")
				.getJSONObject("Product");
		String  price= new JSONObject(JSONArray.fromObject(obj.getString("CatalogList")).get(0).toString()).getString("Price");
		dto.setProductId(bean.getProductId());
		dto.setPrice(new BigDecimal(price));	
		dto.setsecondCategoryId(obj.getInt("CategoryId"));
		products.add(dto);
		cbean.setProducts(products);
		cbean.setAppId("11");
		cbean.setRequestId("22");
		CalculateCall cCall=callCalculated(cbean) ;
		
		System.out.println("userId:"+bean.getUserId());
		System.out.println("productId:"+bean.getProductId());
	}
}
